﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HitchHikersGuideToTheGalaxy.Models
{
    public class PostalCodeRepository : HitchHikersGuideToTheGalaxy.Models.IPostalCodeRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add one PostalCode record to DataBase
        /// </summary>
        /// <param name="postalCode"></param>
        public void Add(PostalCode postalCode)
        {
            db.PostalCodes.InsertOnSubmit(postalCode);
        }

        /// <summary>
        /// Delete one PostalCode record from Database
        /// </summary>
        /// <param name="postalCode"></param>
        public void Delete(PostalCode postalCode)
        {
            db.PostalCodes.DeleteOnSubmit(postalCode);
        }

        /// <summary>
        /// Save changes to database
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Returns all PostalCode objects from Database
        /// </summary>
        /// <returns></returns>
        public IQueryable<PostalCode> FindAllPostalCodes()
        {
            return db.PostalCodes;
        }

        /// <summary>
        /// Returns PostalCode as String
        /// Example output: '101 Reykjavík'
        /// Used for DorpDownBox in registration/edit
        /// </summary>
        /// <returns></returns>
        public IQueryable<string> GetAllPostalCodesForDropDownBox()
        {
            return from p in db.PostalCodes
                   select p.ZipCode + ' ' + p.Town;
        }

        /// <summary>
        /// Skilar einu record af PostalCode útfrá zip code
        /// </summary>
        /// <param name="zipCode"></param>
        /// <returns></returns>
        public PostalCode GetPostalCode(String zipCode)
        {
            return db.PostalCodes.SingleOrDefault(d => d.ZipCode == zipCode);
        }
        
        /// <summary>
        /// Returns zipCode value from postalCode input string
        /// Example input: '101 Reykjavík'
        /// Return example: '101'
        /// </summary>
        /// <param name="postalCode"></param>
        /// <returns></returns>
        public string GetZipCode(string postalCode)
        {
            return postalCode.Substring(0, 3);
        }

        #endregion
    }
}
